/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hisense.settings;


import com.android.internal.os.storage.ExternalStorageFormatter;
import com.android.settings.Utils;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AuthenticatorDescription;
import android.annotation.Patch;
import android.annotation.Patch.Type;
import android.app.Activity;
import android.app.Dialog;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import java.lang.reflect.Method;
import com.google.android.tv.settings.TvSettings;
import com.hisense.settings.util.Wrapper;

import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.settings.R;
/**
 * Confirm and execute a reset of the device to a clean "just out of the box"
 * state.  Multiple confirmations are required: first, a general "are you sure
 * you want to do this?" prompt, followed by a keyguard pattern trace if the user
 * has defined one, followed by a final strongly-worded "THIS WILL ERASE EVERYTHING
 * ON THE PHONE" prompt.  If at any time the phone is allowed to go to sleep, is
 * locked, et cetera, then the confirmation sequence is abandoned.
 *
 * This is the initial screen.
 */
public class SettingsClear extends Activity {
    private static final String TAG = "SettingsClear";

    private static final int KEYGUARD_REQUEST = 55;
	private static final int DIALOG_SETTINGS_RESET = 234;

	private static final int IMAGE_MODE_RESET_VALUE = 0;
	private static final int ASPECTRATIO_MODE_RESET_VALUE = 1;
	private static final int COLORTEMPERATURE_MODE_RESET_VALUE = 0;
	private static final int DYNAMICNOISEREDUCTION_MODE_RESET_VALUE = 1;
	private static final int VALUE_IMAGE_OVERSCAN_OFF = 0;
	private static final int IMAGE_MODE_ENERGYSAVING = 6;
	
	private Wrapper mWrapper = null;
	private Context mContext = null;
    private Button mInitiateButton;
	private CCDisplayOptionSettings ccdisplay;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode != KEYGUARD_REQUEST) {
            return;
        }

        // If the user entered a valid keyguard trace, present the final
        // confirmation prompt; otherwise, go back to the initial state.
        if (resultCode == Activity.RESULT_OK) {
            showFinalConfirmation();
        } else {
            establishInitialState();
        }
    }

    private void showFinalConfirmation() {
        DialogInterface.OnClickListener confirmListener = new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                if (Utils.isMonkeyRunning()) {
                    return;
                }

                sendBroadcast(new Intent("android.intent.action.SETTINGS_CLEAR"));
                // Intent handling is asynchronous -- assume it will happen soon.
            }

        };
		
		showDialog(DIALOG_SETTINGS_RESET);              
    }
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_SETTINGS_RESET: {
                final AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle(R.string.settings_clear_confirm_title)
                .setMessage(R.string.settings_clear_final_desc)
                .setPositiveButton(R.string.settings_clear_final_button_text, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
						resetSettingsData();	
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                    }
                });

                return builder.create();
            }
            default:
                break;
        }
        return super.onCreateDialog(id);
    }

    /**
     * If the user clicks to begin the reset sequence, we next require a
     * keyguard confirmation if the user has currently enabled one.  If there
     * is no keyguard available, we simply go to the final confirmation prompt.
     */

    private Button.OnClickListener mInitiateListener = new Button.OnClickListener() {

        public void onClick(View v) {
            showFinalConfirmation();
        }
    };

    /**
     * In its initial state, the activity presents a button for the user to
     * click in order to initiate a confirmation sequence.  This method is
     * called from various other points in the code to reset the activity to
     * this base state.
     *
     * <p>Reinflating views from resources is expensive and prevents us from
     * caching widget pointers, so we use a single-inflate pattern:  we lazy-
     * inflate each view, caching all of the widget pointers we'll need at the
     * time, then simply reuse the inflated views directly whenever we need
     * to change contents.
     */
    private void establishInitialState() {
        mInitiateButton = (Button) findViewById(R.id.initiate_settings_clear);
        mInitiateButton.setOnClickListener(mInitiateListener);
        Button cancelButton = (Button) findViewById(R.id.cancel);
        cancelButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });

        cancelButton.requestFocus();
    }
	private void resetSettingsData() {
		//image reset
		
		Wrapper.getWrapperInstance().resetPictureMode();
		Wrapper.getWrapperInstance().resetAdvancedPictureMode();
		Wrapper.getWrapperInstance().reSetClosedCaption();
		Log.d("CCDisplayOptionSettings", "ccdisplay = "+ccdisplay);
		ccdisplay.resetcc(0);
		Log.d(TAG, "Privacy & safety------->>>>resetSettingsData ");
		//sound reset
		mWrapper.resetAudioMode(0);
		//time reset
		boolean autoEnabled = getAutoTimeState();
		Log.d(TAG, "autoEnabled "+autoEnabled);
		if (!autoEnabled) {
			Settings.Global.putInt(getContentResolver(), Settings.Global.AUTO_TIME,
                    autoEnabled ? 0 : 1);
			Log.d(TAG, "autoEnabled "+autoEnabled);
//            Settings.System.putInt(getContentResolver(),
//                    Settings.System.AUTO_TIME,
//                    autoEnabled ? 0 : 1);
		}
		//cc reset
		Wrapper.getWrapperInstance().reSetClosedCaption();
		//history 
		sendBroadcastToHistory();

		Wrapper.getWrapperInstance().setAllSourcePictureMode(IMAGE_MODE_ENERGYSAVING);
		TvSettings.Secure.putBoolean(getContentResolver(),"store_mode_enable", false);
	}
	private void sendBroadcastToHistory() {
		Intent intent = new Intent();
		String act = "com.google.tv.settings.CLEAR_HISTORY_SETTING";
		intent.setAction(act);
		sendBroadcast(intent);
	}	
	private boolean getAutoTimeState() {
        try {
            return Settings.Global.getInt(getContentResolver(), Settings.Global.AUTO_TIME)>0;
//					Settings.System.getInt(getContentResolver(),
//                Settings.System.AUTO_TIME) > 0;
        } catch (SettingNotFoundException snfe) {
            return true;
        }
    }

    @Override
    protected void onCreate(Bundle savedState) {
        super.onCreate(savedState);
		mContext = this;
		mWrapper = Wrapper.getWrapperInstance();
        mWrapper.setContext(mContext);
        setContentView(R.layout.settings_clear);
        establishInitialState();
		ccdisplay=new CCDisplayOptionSettings();
    }
}
